<?php

namespace app\service;

use app\core\Service;
use app\model\Member;
use app\model\TeamIncome;
use think\facade\Db;

/**
 * @extends Service<TeamIncomeService>
 */
class TeamIncomeService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        $map = TeamIncome::where($w)->page($page, $limit);
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    //添加收益
    public function addTeamIncome($amount, $memberInfo, $type)
    {
        $member_id = 0;
        $where = $data = [];
        if ($type == 1) {
            $data['commission'] = $amount * ($memberInfo['team_rate'] / 100);
            $memberInfo['team_commission'] = $memberInfo['team_commission'] + $data['commission'];//分销佣金 一级二级分销佣金
            $memberInfo['commission'] = $memberInfo['commission'] + $data['commission'];//总收益
            $member_id = $memberInfo['member_id'];
        }
        $where[] = ['type', '=', $type];
        $where[] = ['member_id', '=', $member_id];
        $where[] = ['date', '=', date('Y-m-d', time())];
        $info = TeamIncome::where($where)->find();
        if ($info) {
            return false;
        }
        Db::startTrans();
        $rs = TeamIncome::create([
            'commission' => $data['commission'],
            'member_id' => $member_id,
            'type' => $type,
            'date' => date('Y-m-d', time()),
        ]);
        if (!$rs) {
            Db::rollback();
            return false;
        }
        $rs = Member::where('member_id', $member_id)->save($memberInfo);
        if (!$rs) {
            Db::rollback();
            return false;
        }

        Db::commit();
        return true;
    }

    public function sumCommission($searchQuery = [])
    {
        $w = [];
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        if (!empty($searchQuery['create_time'])) {
            $time_arr = explode("#", $searchQuery['create_time']);
            if (count($time_arr) > 0) {
                $w[] = ['create_time', 'between', $time_arr];
            }
        }
        $commission = TeamIncome::where($w)->sum('commission');
        return $commission;
    }

}